<template>
  <BaseDialog
    v-model:visible="visible"
    title="用户注册"
    icon="UserPlus"
    width="500px"
    :show-footer="false"
    :close-on-click-modal="false"
    @close="resetForm"
  >
    <div class="register-form">
      <!-- 注册表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="邮箱" prop="email">
          <BaseInput
            v-model="form.email"
            type="email"
            placeholder="请输入邮箱地址"
            prefix-icon="Message"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <BaseInput
            v-model="form.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <BaseInput
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <BaseInput
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item label="昵称（可选）" prop="nickname">
          <BaseInput
            v-model="form.nickname"
            placeholder="请输入昵称"
            prefix-icon="Avatar"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <div class="register-agreement">
            <el-checkbox v-model="form.agreeToTerms" size="small">
              我已阅读并同意
            </el-checkbox>
            <el-button type="text" size="small" @click="showUserAgreement = true">
              《用户协议》
            </el-button>
            <span>和</span>
            <el-button type="text" size="small" @click="showPrivacyPolicy = true">
              《隐私政策》
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <!-- 注册按钮 -->
      <div class="register-actions">
        <BaseButton
          type="primary"
          size="large"
          block
          :loading="loading"
          :disabled="!form.agreeToTerms"
          @click="handleSubmit"
        >
          注册账号
        </BaseButton>
      </div>

      <!-- 注册提示 -->
      <div class="register-tips">
        <el-alert
          type="info"
          :closable="false"
          show-icon
        >
          <template #title>
            <span class="tip-text">注册成功后，我们将向您的邮箱发送验证邮件</span>
          </template>
        </el-alert>
      </div>

      <!-- 切换到登录 -->
      <div class="auth-switch">
        <span class="switch-text">已有账号？</span>
        <el-button type="text" @click="$emit('switch-to-login')">
          立即登录
        </el-button>
      </div>
    </div>

    <!-- 用户协议弹窗 -->
    <UserAgreement 
      v-model="showUserAgreement" 
      @agree="handleAgreeTerms" 
    />

    <!-- 隐私政策弹窗 -->
    <PrivacyPolicy 
      v-model="showPrivacyPolicy" 
      @agree="handleAgreePrivacy" 
    />
  </BaseDialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/user'
import { Message, User, Lock, Avatar } from '@element-plus/icons-vue'
import BaseDialog from '../common/BaseDialog.vue'
import BaseInput from '../common/BaseInput.vue'
import BaseButton from '../common/BaseButton.vue'
import UserAgreement from '../legal/UserAgreement.vue'
import PrivacyPolicy from '../legal/PrivacyPolicy.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'update:modelValue', 
  'success', 
  'switch-to-login'
])

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const showUserAgreement = ref(false)
const showPrivacyPolicy = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  email: '',
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  agreeToTerms: false
})

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
      message: '密码必须包含大小写字母和数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return

  if (!form.agreeToTerms) {
    ElMessage.warning('请先同意用户协议和隐私政策')
    return
  }

  try {
    await formRef.value.validate()
    loading.value = true

    const result = await userStore.register({
      username: form.username,
      email: form.email,
      password: form.password,
      confirmPassword: form.confirmPassword,
      nickname: form.nickname || form.username
    })

    if (result.success) {
      ElMessage.success('注册成功！请查收邮箱验证邮件')
      visible.value = false
      emit('success')
      // 注册成功后可以选择自动切换到登录页面
      setTimeout(() => {
        emit('switch-to-login')
      }, 1500)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    agreeToTerms: false
  })
}

const handleAgreeTerms = () => {
  // 当用户同意用户协议时的处理
  ElMessage.success('感谢您阅读用户协议')
}

const handleAgreePrivacy = () => {
  // 当用户同意隐私政策时的处理
  ElMessage.success('感谢您阅读隐私政策')
}
</script>

<style scoped>
.register-form {
  padding: 0;
  max-height: 100%;
  overflow: visible;
}

.register-agreement {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  line-height: var(--line-height-normal);
}

.register-actions {
  margin: var(--spacing-xl) 0 var(--spacing-lg);
}

.register-tips {
  margin-bottom: var(--spacing-lg);
}

.tip-text {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.auth-switch {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: var(--spacing-sm);
  padding-top: var(--spacing-xl);
  border-top: 1px solid var(--color-border-light);
}

.switch-text {
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-sm);
}

:deep(.el-checkbox) {
  color: var(--color-text-secondary);
}

:deep(.el-checkbox__label) {
  font-size: var(--font-size-sm);
}

:deep(.el-alert) {
  border-radius: var(--radius-md);
  border: 1px solid var(--color-info-200);
  background: var(--color-info-50);
}

:deep(.el-alert__icon) {
  color: var(--color-info);
}

:deep(.el-alert__title) {
  color: var(--color-text-secondary);
}

/* 密码强度提示 */
.password-strength {
  margin-top: var(--spacing-xs);
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

.password-strength.weak {
  color: var(--color-error);
}

.password-strength.medium {
  color: var(--color-warning);
}

.password-strength.strong {
  color: var(--color-success);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-agreement {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .auth-switch {
    flex-direction: column;
    gap: var(--spacing-xs);
  }
}
</style>
